import traceback
from flask import Blueprint,render_template,jsonify,request,abort,send_from_directory,make_response
from sqlalchemy import func, and_
from werkzeug.wrappers import response
import  models
from urllib.parse import quote, urldefrag
import json
from werkzeug.serving import WSGIRequestHandler
WSGIRequestHandler.protocol_version = "HTTP/1.1"
from werkzeug.utils import secure_filename
import os
import config
from config import debug, log as log
from config import makeNewSession, safe_file_name
import re
from uuid import uuid4
from datetime import datetime,timedelta
import pypandoc # 文件格式转换操作

files = Blueprint('files',__name__)


@files.route("/uploadFile", methods=["POST"])
def uploadSendFile():
    # print(request.args)
    # print(request.headers)
    # print(request.files)
    if request.method == 'POST':
        session = makeNewSession()
        f = request.files['file']
        print("fileName",f.filename)
        ext = os.path.splitext(f.filename)[1]
        newFileName = f"{uuid4().hex}{ext}"
        print("newFileName",newFileName)
        # basepath = os.path.dirname(__file__)  # 当前文件所在路径
        upload_path = os.path.join(config.UPLOADDIR,newFileName)  #注意：没有的文件夹一定要先创建，不然会提示没有该路径
        f.save(upload_path)
        
        fi = models.File(userFileName=f.filename,serverFileName=newFileName,fileSize=os.path.getsize(upload_path))
        session.add(fi)
        session.commit()
        session.close()


        return jsonify({"code":0,"data":[{"fp_relative":secure_filename(f.filename)}]})
    return jsonify({"code":1,"data":[]})


# 获取文件库
@files.route("/fileLib")
def fileLib():
    curPage = request.args.get("page",1,type=int)
    per_page = request.args.get("limit",15,type=int)
    getData = json.loads(request.args.get("searchParams","{}"))
    print(getData, bool(getData),"text",getData)
    session = makeNewSession()
    if getData:
        stime = getData.get("datetime",None)
        if not stime: stime = f"2022-01-03 - {(datetime.now()+timedelta(4)).date()}"
        stime  = stime.split(" - ") 
        print("stime",stime)
        condition = and_(
            models.File.userFileName.contains(getData.get("userFileName", '')) if getData.get("userFileName", '') else True,
            models.File.beizhu.contains(getData.get("beizhu", '') ) if getData.get("beizhu", '') else True,
            models.File.datetime >= stime[0],
            models.File.datetime <= stime[1]
        )

    # 分页
    all_ = session.query(models.File).offset((curPage-1)*per_page).limit(per_page)   if not getData else session.query(models.File).filter(condition).offset((curPage-1)*per_page).limit(per_page)  

    # count  = session.query(func.count(all_)).scalar()
    # 获取总条数
    count =session.query(func.count(models.File.fileID)).scalar() if not getData else session.query(func.count(models.File.fileID)).filter(condition).scalar()

    result = {
        "code": 0,
        "msg": "",
        "count": count,
        "data": []
        }
    debug("all_",all_)
    for each in all_:
        result['data'].append(each.to_json())
    session.close()
    return jsonify(result)

# 删除文件信息
@files.route("/delFileData",methods=["POST"])
def delFileData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    session = makeNewSession()
    try:
        q = session.query(models.File).filter(models.File.fileID==getData['fileID']).first()
        fPath = os.path.join(config.UPLOADDIR,q.serverFileName)
        # print("fPath", fPath)
        if os.path.exists(fPath):
            os.remove(fPath)
        session.delete(q)
        session.commit()
        session.close()
        return "del successfully"
    except:
        traceback.print_exc()
        session.rollback()
        session.close()
        return "del failure",500

# 删除文件 多
@files.route("/delFilesData",methods=["POST"])
def delFilesData():
    getDatas = request.get_json()
    # print(getDatas)
    session = makeNewSession()
    try:
        qs = session.query(models.File).filter(models.File.fileID.in_(getDatas))
        for each in qs:
            fPath = os.path.join(config.UPLOADDIR,each.serverFileName)
            # print("fPath", fPath)
            if os.path.exists(fPath):
                os.remove(fPath)
            
        qs.delete()
        session.commit()
        session.close()
        return "del successfully"
    except:
        session.rollback()
        session.close()
        return "del failure",500

# 更新文件信息
@files.route("/updateFileData",methods=["POST"])
def updateFileData():
    getData = request.get_json()
    if not getData: return "you need post some args!",406
    print(getData)
    session = makeNewSession()
    try:
        session.query(models.File).filter(models.File.fileID==getData["fileID"]).update(getData)
        session.commit()
        session.close()
        return "update successfully"
    except:
        session.rollback()
        session.close()
        return "update failure",500

# 文件下载
@files.route("/filedownload")
def filedownload():
    if request.method=="GET":
        id_ = request.args.get("id",None,type=int)
        if not id_:
            return render_template("404.html"),404
        session = makeNewSession()
        q = session.query(models.File).filter(models.File.fileID==id_).first()
        session.close()
        if not q:
            return render_template("404.html"),404
        fPath = os.path.join(config.UPLOADDIR, q.serverFileName)
        if os.path.isfile(fPath):
            # r = re.sub(r"[^\u4e00-\u9fa5a-zA-Z0-9_\.]","_",q.userFileName)
            r = safe_file_name(q.userFileName)
            s = send_from_directory(config.UPLOADDIR,q.serverFileName,as_attachment=True)
            s.headers["Content-Disposition"] = f"attachment; filename={quote(r)}"
            return s
    return render_template("404.html"),404

# 本地文件转html
@files.route("/to_html")
def to_html():    
    if request.method=="GET":
        id_ = request.args.get("id",None,type=str)
        if not id_:
            return "you need arg id"
        session = makeNewSession()
        if id_.isdigit():
            id_=int(id_)
            q = session.query(models.File).filter(models.File.fileID==id_).first()
            session.close()
            if not q:
                return render_template("404.html")
            fPath = os.path.join(config.UPLOADDIR, q.serverFileName)
        else:
            q = session.query(models.FormTableUploadFile).filter(models.FormTableUploadFile.fileID==id_).first()
            session.close()
            if not q:
                return render_template("404.html")

            
            fPath = os.path.join(config.FORM_UPLOAD_FILES_DIR, f"formTable{id_.split('_')[0]}",q.serverFileName)

        print("fpath",fPath)
        if q.serverFileName.lower().endswith(('.bmp', '.dib', '.png', '.jpg', '.jpeg', '.pbm', '.pgm', '.ppm', '.tif', '.tiff')):
            dir, fname = os.path.split(fPath)
            return send_from_directory(dir, fname)
        if os.path.isfile(fPath):
            return pypandoc.convert_file(fPath, 'html',encoding='utf-8')
        
    return ""